package com.xms.event.core;

import com.baomidou.mybatisplus.extension.activerecord.Model;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * ConsumerFactory
 * </p>
 *
 * @author migo
 * @since 2021/10/11
 */
public class ConsumerFactory {
    private static ConcurrentHashMap<String, List<IConsumer>> consumers = new ConcurrentHashMap<>();

    public static void add(IConsumer consumer){
        ParameterizedType thisType = (ParameterizedType)consumer.getClass().getGenericInterfaces()[0];
        String key = thisType.getActualTypeArguments()[0].getTypeName();
        if(thisType.getActualTypeArguments()[0] instanceof ParameterizedType
        && !((ParameterizedType)thisType.getActualTypeArguments()[0]).getClass().isAssignableFrom(Model.class))
        {
            //如果泛型参数T为运行时指定的，则为公共消费者
            key = ((ParameterizedType)thisType.getActualTypeArguments()[0]).getRawType().getTypeName();
        }
        if(consumers.containsKey(key)){
            List<IConsumer> items = consumers.get(key);
            items.add(consumer);
            consumers.replace(key, items);
        }
        else {
            consumers.put(key, new ArrayList<IConsumer>() {{
                add(consumer);
            }});
        }
    }

    public static <TEvent> List<IConsumer> get(TEvent e){
        return consumers.get(e.getClass().getTypeName());
    }
}
